#===============================================================================
# Koro Business Environment
# Copyright (C) 2008  Antonio Corroppoli
#
#This file is part of Koro BE.
# 
# Koro BE is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# Koro BE is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Koro BE; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#===============================================================================
print 'import session'
#from decimal import Decimal

from sqlalchemy import create_engine,Table,MetaData
from sqlalchemy.orm import sessionmaker,mapper,relation 

#from koro.db import tables

from koro.core import model
from koro import ksettings
from koro.db.persister import ObjectPersister

#import MySQLdb
#import gap.gException as gException
#from gap.gConstants import TS_ , TS_INS, TS_MOD
#from gBackend import gBackend,gSelectInfo,gInsertInfo,gDeleteInfo
#import gNoEscQuoteStr as gNoEQ
#from gTable import gTableOpt
#conn_info={'backend':'mysql',
#           'dbname':'koro',
#           'host':'localhost',
#           'port':3306,
#           'user':'root',
#           'passwd':'or8pale12'
#           }

class Session(object):
    def __init__(self):        
        self._Session = None#sessione di passaggio. e' la classe Session di sqlalchemy
        self.__session=None#sessione normale
        self.__db_session=None#sessione per comunicare col db bsddb
    
    def configure(self,configuration):
        #connection info
        if not self.get_connection_info():
            self.__configure_connection_info()
        conn_info=self.get_connection_info()
            #{backend}://{user}:{passwd}@{host}:{port}/{dbname}
        #engine=create_engine('{backend}://{user}{passwd}{host}{port}/{dbname}'.format(**conn_info),
#        engine=create_engine('sqlite:////home/antstud/Scaricati/sqlite3/koro.db',
        engine=create_engine('sqlite:///{0}'.format(ksettings.DB_PATH),
                             convert_unicode=True)
        metadata=MetaData(bind=engine)
        
               
#        mapper(models.Indirizzo,Table('indirizzi',metadata,autoload=True))
        
        mapper(model.Opzione,Table('opzioni',metadata,autoload=True))
        configuration.configure_orm(mapper,relation,metadata,Table)
        
        self._Session=sessionmaker(bind=engine)
        self.__session=self._Session()
        
    def __configure_connection_info(self):
        info=model.InfoConnessione()
        self.save_connection_info(info)
        
    def get_current_session(self):
        '''Restituisce la sessione globale. non deve essere chiusa.'''       
        return self.__session
    
    def get_session(self):
        '''Restituisce una nuova sessione configurata come la sessione globale. Deve essere chiusa.'''
        return self._Session()
    
    def get_connection_info(self):
        ObjectPersister.use(ksettings.KOROBE_CFG)
        return ObjectPersister.get('CI')
    
    def save_connection_info(self,info):
        assert isinstance(info,model.InfoConnessione)
        ObjectPersister.use(ksettings.KOROBE_CFG)
        ObjectPersister.put('CI',info)
    
    def close(self):
        print 'chiusura sessione database'
        self.__session.close()
    